import { base64_decode } from 'ourwill-feutil/common/base64';
import { getCookie, setCookie } from 'ourwill-feutil/broswer/cookie';
export const getAuthToken = () => {
	const tokenData = localStorage.getItem('authToken') || getCookie('Auth-token');
	if (!tokenData) {
		return '';
	}
	try {
		// 防止中途因为各种问题报错,只要报错,直接置为'', 防止逻辑出现中断
		const tokenOption = tokenData.split('.')[1];
		const tokenSetInfo = JSON.parse(base64_decode(tokenOption));
		if (!tokenSetInfo) {
			return '';
		}
		let authToken = '';
		const { exp } = tokenSetInfo;
		const expires = exp * 1000;
		if (expires > new Date().getTime()) {
			authToken = tokenData;
		}
		return authToken;
	} catch (error) {
		console.error('auth token get error: ', error);
		return '';
	}
};
export const setAuthToken = (token: string) => {
	const tokenData = localStorage.getItem('authToken');
	if (!tokenData || tokenData !== token) {
		localStorage.setItem('authToken', token);
	}
};

export const clearAuthToken = () => {
	localStorage.removeItem('authToken');
	setCookie('Auth-token', '', 0);
};
